home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5159 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: gail.ripco.com!mambuhl
  2. From: mambuhl@ripco.com (Martin Ambuhl)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: free space malloced t
  5. Date: 7 Feb 1996 16:40:39 GMT
  6. Organization: Ripco Communications, Inc.
  7. Message-ID: <4fakm7$247@gail.ripco.com>
  8. NNTP-Posting-Host: foley.ripco.com
  9.  
  10. matmrlx@gsusgi1.gsu.edu (Michael R. Lauer)
  11. in <4eqf8m$smv@gsusgi1.gsu.edu> asks:
  12.  
  13. >The general question is: if you malloc space for a pointer with automatic
  14. >storage, should/must you free that space before leaving that scope?
  15.  
  16. Only if _you_ allocate the space.
  17.  
  18. >This seems obvious but it is giving me trouble. In this code:
  19.  
  20. >{
  21. >        struct dirent *dp;
  22. >        if ((dp = readdir() != NULL)
  23.                    ^^^^^^^^^
  24. OK...since readdir() is not a standard C function, I can't _know_ that
  25. this is an error, but in the implementations I use, the prototype for
  26. readdir is
  27.     struct dirent readdir(DIR *dirp);
  28.  
  29. >        {
  30. >        }
  31. >        if (dp)                         /* this seems to cause a segmentation f
  32. >                free(dp);               /* when the enclosing function returns
  33. >}
  34.  
  35. _You_ are not allocating the space.  Handle the memory you allocate.  If
  36. some other function allocates the space it is responsible for making
  37. sure its usage is safe.
  38.  
  39. >So readdir returns a pointer to the dirent structure--it is mallocing the
  40. >space....
  41.  
  42. How do you know this?  In the implementations that I use, the struct
  43. dirent is allocated as a member of the DIR (which you omitted in the
  44. call to readdir()).  It is also possible that it is a static struct.  If
  45. your call to readdir() is right for your implementation, this only
  46. underlines why non-standard C is a problem in comp.lang.c.
  47.  
  48.               
  49. --
  50. * Martin Ambuhl       net: mambuhl@ripco.com
  51. * Chicago, IL (USA)    
  52.